#!/bin/sh
### BEGIN INIT INFO
# Provides:          lkp-bootstrap
# Required-Start:    $all
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: LKP bootstrap
# Description:       LKP bootstrap
### END INIT INFO

# Call this script at boot time.
# Keep it simple and stupid -- it will be installed in a number of rootfs.

# We can install lkp-bootstrap several places, so that at least one of them can
# take effect in a particular rootfs, and the follow up ones can check reboot
# the machine if the former one failed to do so.

# Check if the process is already running
if [ -s /lkp/run/lkp-bootstrap.pid ]; then
	pid=$(cat /lkp/run/lkp-bootstrap.pid)
	if [ -d "/proc/$pid" ]; then
		exit 0
	fi
	# The previous lkp-bootstrap init.d script failed to restart the machine
	echo "LKP bootstrap: first run may have failed, retry rebooting"
	reboot
	exit 0
fi

# Function to read kernel command line variables
read_kernel_cmdline_vars() {
	[ -f /proc/cmdline ] || return 1

	for i in $(cat /proc/cmdline); do
		case "$i" in
			user=*|job=*|ip=*|NO_NETWORK=*|result_service=*)
				export "$i"
				;;
		esac
	done
	return 0
}

# Read kernel command line variables
read_kernel_cmdline_vars

# Set the job file path
[ -n "$job" ] || export job=/lkp/scheduled/job.yaml
[ -e "$job" ] || export job=$(echo /lkp/scheduled/*.yaml)
[ -e "$job" ] || export job=$(echo /lkp/jobs/scheduled/*/*.yaml)

# Determine the job script path
if [ "${job%.yaml}" != "$job" ]; then
	export job_script="${job%.yaml}.sh"
else
	export job_script="$job"
fi

# Ensure the job script exists
[ -e "$job_script" ] || {
	echo "$job_script does not exist, quit from LKP"
	exit 0 # to work with non-LKP boots
}

# Set default user and LKP environment variables
: "${user:=lkp}"
export LKP_USER="$user"
export LKP_SRC="/lkp/$user/src"

# Enable debugging if specified
[ -n "$BASHPID" ] && export PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'
set +m

# Source necessary scripts
. "$LKP_SRC/lib/env.sh"
. "$job_script"

# Export top environment and read job variables if commands exist
if has_cmd export_top_env; then
	export_top_env
fi
if has_cmd read_job_vars; then
	read_job_vars
fi

# Enable debug mode if specified
if [ -n "$debug_lkp$DEBUG_LKP" ]; then
	[ "$debug_lkp$DEBUG_LKP" -ge 2 ] && set -x
	[ "$debug_lkp$DEBUG_LKP" -ge 1 ] && export DEBUG_LKP_PREFIX='bash -x'
fi

# Handle Docker environment
if is_docker; then
	$DEBUG_LKP_PREFIX "$LKP_SRC/bin/lkp-setup-rootfs" && exit 0
fi

# Run setup in the background
(
	$DEBUG_LKP_PREFIX "$LKP_SRC/bin/lkp-setup-rootfs" && exit 0

	# Allow time for debugging before rebooting
	sleep 10m &&
	reboot
) &

# Save the background process PID
mkdir -p /lkp/run
echo $! > /lkp/run/lkp-bootstrap.pid
